package com.mayikt.days06;

import java.util.concurrent.locks.LockSupport;

/**
 * @ClassName MayiktFutureTask
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class MayiktFutureTask<V> implements Runnable {
    private MayiktMTCallable<V> mayiktMTCallable;
    // callable 对应的返回结果
    private V result;

    private Thread cuThread;
    private Object lock = new Object();

    public MayiktFutureTask(MayiktMTCallable<V> mayiktMTCallable) {
        this.mayiktMTCallable = mayiktMTCallable;
    }

    @Override
    public void run() {
        // 执行我们的
        if (mayiktMTCallable != null) {
            try {
                result = mayiktMTCallable.call();
//                if (result != null) {
//                    // call 唤醒阻塞的线程
//                    LockSupport.unpark(cuThread);
                    synchronized (lock) {
                        lock.notify();
                    }

//                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public V get() {
        // 如果Callable 返回结果为空的情况下， 则当前调用get方法的线程会变为阻塞状态
        if (result != null) {
            return result;
        }
        // 让当前的主线程变为阻塞状态
        cuThread = Thread.currentThread();
//        LockSupport.park(cuThread);
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
